﻿// 文件使用MiniExcel源码， 使用时需遵循其 Apache License 2.0
// 修改摘要通知： 删除异步、Task等net2.0中不支持的内容，替换原先C#自带的zip处理方式，改用yacomp 进行解压缩。
using System;
using System.Text;
using System.Xml;
    
namespace ExcelConfig.Utils
{
    internal static class StringHelper
    {
        private static readonly string[] _ns = { OpenXml.Config.SpreadsheetmlXmlns, OpenXml.Config.SpreadsheetmlXmlStrictns };

        internal static string GetLetters(string content)
        {
            var outp = new StringBuilder();
            for(var i = 0; i < content.Length; i++) if (char.IsLetter(content[i])) outp.Append(content[i]); 
            return outp.ToString();
        }
        internal static int GetNumber(string content)
        {
            var outp = new StringBuilder();
            for (var i = 0; i < content.Length; i++) if (char.IsNumber(content[i])) outp.Append(content[i]);
            return int.Parse(outp.ToString());
        }

        /// <summary>
        /// Copied and modified from ExcelDataReader - @MIT License
        /// </summary>
        internal static string ReadStringItem(XmlReader reader)
        {
            var result = new StringBuilder();
            if (!XmlReaderHelper.ReadFirstContent(reader))
                return string.Empty;

            while (!reader.EOF)
            {
                if (XmlReaderHelper.IsStartElement(reader, "t", _ns))
                {
                    // There are multiple <t> in a <si>. Concatenate <t> within an <si>.
                    result.Append(reader.ReadElementContentAsString());
                }
                else if (XmlReaderHelper.IsStartElement(reader, "r", _ns))
                {
                    result.Append(ReadRichTextRun(reader));
                }
                else if (!XmlReaderHelper.SkipContent(reader))
                {
                    break;
                }
            }

            return result.ToString();
        }

        /// <summary>
        /// Copied and modified from ExcelDataReader - @MIT License
        /// </summary>
        private static string ReadRichTextRun(XmlReader reader)
        {
            var result = new StringBuilder();
            if (!XmlReaderHelper.ReadFirstContent(reader))
                return string.Empty;

            while (!reader.EOF)
            {
                if (XmlReaderHelper.IsStartElement(reader, "t", _ns))
                {
                    result.Append(reader.ReadElementContentAsString());
                }
                else if (!XmlReaderHelper.SkipContent(reader))
                {
                    break;
                }
            }

            return result.ToString();
        }
    }
}
